﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using Welcome.Dialog; 
namespace Welcome
{
    public partial class CreateFolder : Form
    {
        /// <summary>
        /// 数据
        /// </summary>
        #region 全局数据
        string path = "";
        string name = "";
        string xml = "";
        public static string xmlsavepath ="";  //保存路径
        public static string exepath = "";   //程序所在的路径
        public static TreeView treenode;
        private bool isreminddelete = false;  //删除节点是否提醒
        #endregion

        //客户区移动
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        public CreateFolder()
        {
            Welcome dlg = new Welcome();   //打开欢迎界面
            dlg.ShowDialog(); 

            InitializeComponent();
            init();  //初始化
           
        }

        /// <summary>
        /// user-defined
        /// </summary>
        #region 功能函数
        //初始化
        private void init()
        {
            //窗口样式
            this.FormBorderStyle = FormBorderStyle.None;
            this.StartPosition = FormStartPosition.CenterScreen; //居中
            this.TopMost = false;

            cb_remindcreatepath.Checked = true;
            cb_reminddelete.Checked = true;
            cb_openfolder.Checked = true;   //生成后打开文件夹
            tree_folder.LabelEdit = true;//可编辑状态。
            /// <summary>
            /// 配置文件
            /// </summary>
#region 配置文件
            exepath = System.Environment.CurrentDirectory;  //获得路径
            xmlsavepath = path;
            if (File.Exists(exepath + "\\setting.ini"))//配置文件存在
            {
                IniUtil ini = new IniUtil(exepath + "\\setting.ini");
                path = ini.IniReadValue("defaultcreatepath", "value");
                name = ini.IniReadValue("defaultfilename", "value");
                xml = ini.IniReadValue("defaultxml", "value");
            }
            else
            {
                IniUtil ini = new IniUtil(exepath + "\\setting.ini");
                ini.IniWriteValue("defaultcreatepath", "value", "C:\\Users\\Administrator\\Desktop");
                ini.IniWriteValue("defaultfilename", "value", "新建文件夹");
                ini.IniWriteValue("defaultxml", "value", exepath + "\\MyTemplate.xml");
                path = "C:\\Users\\Administrator\\Desktop";
                name = "新建文件夹";
                xml = exepath + "\\MyTemplate.xml";
            }
            if (File.Exists(xml))//配置文件存在
            {
                XmlUtil a = new XmlUtil();
                a.XMLToTree(tree_folder, xml);
            }
            else
            {
                xml = exepath + "\\MyTemplate.xml";
            }
            xmlsavepath = xml;
            tb_createpath.Text = path;
            tb_nodetitle.Text = name;
            treenode = tree_folder;
#endregion
        }
        //添加
        private string getnewnodetitle(int stype)
        {
            string newnodetitle = tb_nodetitle.Text;
            if (newnodetitle == "")
            {
                tb_nodetitle.Text = "新建文件夹";
                newnodetitle = "新建文件夹";
            }
            //计算同级节点中是否有相同名称
            switch (stype)
            {
                case 0:   //根节点下
                    foreach (TreeNode node in tree_folder.Nodes)
                    {
                        newnodetitle = IsNameRepeat(newnodetitle, node);
                    }
                    break;
                case 1:  //选择节点下
                    foreach (TreeNode node in tree_folder.SelectedNode.Nodes)
                    {
                        newnodetitle = IsNameRepeat(newnodetitle, node);
                    }
                    break;
                case 2:  //根节点下选择节点下
                    foreach (TreeNode node in tree_folder.SelectedNode.Parent.Nodes)
                    {
                        newnodetitle = IsNameRepeat(newnodetitle, node);
                    }
                    break;
            }

            return newnodetitle;

        }
        /// <summary>
        /// 遍历节点
        /// </summary>
        /// <param name="aNodes">tree对象</param>
        /// <param name="IsCreateFolder">是否创建文件夹</param>
        /// <param name="filepath">文件夹最上层路径</param>
        /// 示例
        /// ergodTree(tree_folder.Nodes,true,tb_createpath.Text);
        public void ErgodTree(TreeNodeCollection aNodes , bool IsCreateFolder ,string filepath)
        {
            string path = "";
            foreach (TreeNode iNode in aNodes)
            {
                if(IsCreateFolder)      //相对上层节点
                {
                    //MessageBox.Show(filepath + "\\" + iNode.Text);
                    string filename = iNode.Text;
                    path = filepath + "\\" + filename;    //当前生成文件夹的全路径 D:\123
                    if (!Directory.Exists(path))//判断文件夹是否已经存在
                    {
                        //去除文件中非法字符
                        StringBuilder rBuilder = new StringBuilder(filename);
                        foreach (char rInvalidChar in Path.GetInvalidFileNameChars()) 
                            rBuilder.Replace(rInvalidChar.ToString(), string.Empty);
                        Directory.CreateDirectory(filepath + "\\" + filename);//创建文件夹
                    }
                }
                if (iNode.Nodes.Count > 0)  //相对下层节点
                {
                   ErgodTree(iNode.Nodes, IsCreateFolder, path);
                }
            }
        }
        //节点下是否有重复名称的节点
        private string IsNameRepeat(string newnodetitle, TreeNode node)
        {
            if (node.Text.Equals(newnodetitle))
            {
                System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
                string numstr = "";  //数字
                int numcount = 0; //数字位数
                for (int i = 1; reg1.IsMatch("" + newnodetitle[newnodetitle.Length - i]); i++)
                {
                    numstr = "" + newnodetitle[newnodetitle.Length - i] + numstr;
                    numcount++;
                }
                if (numstr != "")
                {
                    int num = int.Parse(numstr);
                    newnodetitle = newnodetitle.Substring(0, newnodetitle.Length - numcount);
                    num++;
                    newnodetitle = newnodetitle + "" + num;
                }
                else
                {
                    newnodetitle = newnodetitle + "1";
                }
            }
            return newnodetitle;
        }
        #endregion

        /// <summary>
        /// system
        /// </summary>
        //鼠标按下
        private void CreateFolder_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);//客户区移动
        }
        //鼠标点击节点
        private void NodeClick(object sender, TreeNodeMouseClickEventArgs e)
        {
           
        }
        //导入
        private void btn_import_Click(object sender, EventArgs e)
        {
            string filepath = "";
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                filepath = dialog.FileName;
                tree_folder.Nodes.Clear();
                XmlUtil a = new XmlUtil();
                a.XMLToTree(tree_folder, filepath);
                
                xmlsavepath = filepath;
                IniUtil ini = new IniUtil(exepath + "\\setting.ini");
                ini.IniWriteValue("defaultxml", "value", xmlsavepath);
            }
        }
        //导出
        private void btn_export_Click(object sender, EventArgs e)
        {
            Save dlg = new Save();
            dlg.ShowDialog(this);
            //Welcome.static_Welcome.Close();   //关闭欢迎界面
        }
        //展开
        private void btn_unfold_Click(object sender, EventArgs e)
        {
            tree_folder.ExpandAll();
        }
        //折叠
        private void btn_fold_Click(object sender, EventArgs e)
        {
            tree_folder.CollapseAll();
        }
        //添加子节点
        private void btn_addchild_Click(object sender, EventArgs e)
        {
                if (tree_folder.SelectedNode == null)   //选择节点为空
                {
                    if (tree_folder.Nodes[0] == null)   //第一个节点也为空，则创建
                    {
                        TreeNode node = new TreeNode();
                        node.Text = getnewnodetitle(0);
                        tree_folder.Nodes.Add(node);
                    }
                    else
                    {
                        tree_folder.SelectedNode = tree_folder.Nodes[0];
                        TreeNode node = new TreeNode();
                        node.Text = getnewnodetitle(1);
                        tree_folder.SelectedNode.Nodes.Add(node);
                        tree_folder.SelectedNode.Expand();
                    }
                }
                else
                {
                    TreeNode node = new TreeNode();
                    node.Text = getnewnodetitle(1);
                    tree_folder.SelectedNode.Nodes.Add(node);
                    tree_folder.SelectedNode.Expand();
                }
        }
        //添加根节点
        private void btn_addboot_Click(object sender, EventArgs e)
        {
            TreeNode node = new TreeNode();
            node.Text = getnewnodetitle(0);
            tree_folder.Nodes.Add(node);
        }
        //删除
        private void btn_delete_Click(object sender, EventArgs e)
        {
            if (!cb_reminddelete.Checked)
            {
                if (tree_folder.SelectedNode != null)
                    tree_folder.Nodes.Remove(tree_folder.SelectedNode);
            }
            else
            {
                if (tree_folder.SelectedNode != null)
                {
                    if (MessageBox.Show("确认删除？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        tree_folder.Nodes.Remove(tree_folder.SelectedNode);
                    }
                    else
                    {
                        return;//返回 
                    }
                }    
            } 
        }
        //浏览
        private void btn_browse_Click(object sender, EventArgs e)
        {
             System.Windows.Forms.FolderBrowserDialog folder = new System.Windows.Forms.FolderBrowserDialog();

             if (folder.ShowDialog() == DialogResult.OK)
             {
                 tb_createpath.Text = folder.SelectedPath;
             }
        }
        //生成
        private void btn_create_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(tb_createpath.Text))//判断文件夹是否已经存在
            {
                MessageBox.Show("文件路径非法");
                return;
            }
            ErgodTree(tree_folder.Nodes, true, tb_createpath.Text);   //遍历生成
            if (cb_openfolder.Checked)   //生成后打开文件夹
                System.Diagnostics.Process.Start(tb_createpath.Text);

            if (cb_remindcreatepath.Checked)
            {
                IniUtil ini = new IniUtil(exepath + "\\setting.ini");
                ini.IniWriteValue("defaultcreatepath", "value", tb_createpath.Text);
                ini.IniWriteValue("defaultfilename", "value", tb_nodetitle.Text);
            }
            MessageBox.Show("生成成功");
        }
        //关闭
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //置顶
        private void btn_topmost_Click(object sender, EventArgs e)
        {
            if (btn_topmost.Text.Equals("底"))
            { //置顶
                btn_topmost.Text = "顶";
                this.TopMost = true;
            }
            else
            {
                btn_topmost.Text = "底";
                this.TopMost = false;
            }
        }
        //双击节点
        private void NodeDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (tree_folder.SelectedNode != null)
                tree_folder.SelectedNode.BeginEdit();
        }
        //删除节点是提醒
        private void cb_reminddelete_CheckedChanged(object sender, EventArgs e)
        {
            if (cb_reminddelete.Checked)
            {
                isreminddelete = true;
            }
            else
            {
                isreminddelete = false;
            }
        }

        private void Tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //MessageBox.Show("123123");
        }
        //控件变化
        private void Tree_AfterEdit(object sender, NodeLabelEditEventArgs e)
        {
            //MessageBox.Show("222");
            if(exepath != null)
            {
                string str = exepath + "//备份.xml";
                XmlUtil a = new XmlUtil();
                a.TreeToXML(tree_folder, str);
            }
           
          
        }
      
    }
}
